/*
 * @(#)TriggerWorkflowAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.rules.action;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.mandarax.eca.ActionException;

import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.EmailMessageToRule;
import com.dcivision.dms.core.DocumentEmailArchiveManager;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.mail.bean.EmailAttachmentImpl;
import com.dcivision.mail.bean.EmailMessageImpl;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.user.bean.UserRecord;


/**
 * <p>Class Name:  TriggerWorkflowAction </p>
 * <p>Description: This class will trigger a workflow.</p>
 * 
 * @author         Beyond Qu
 * @company        DCIVision Limited
 * @creation date  29/07/2005
 * @version        $Revision: 1.11.4.2 $
 */
public class SaveEmailToDMSAction extends AbstractRuleAction {

  private String parentID = "";
  private String rootID = "";
  
  
  /**
   * Constructor.
   */
  public SaveEmailToDMSAction() {
    super();
  }

  /**
   * Perform an action.
   * @param param the action parameters
   */
  public void perform(Object[] param) throws ActionException {
    log.debug("================= SaveEmailToDMSAction perform Strat ====================");
    Connection dbConn = null;

    try{
      dbConn = DataSourceFactory.getConnection();
      SessionContainer sessionContainer = this.getSessionContainer();
      
      //set user
      UserRecord tmpUserRecord = new UserRecord();
      tmpUserRecord.setID(new Integer(0));
      sessionContainer.setUserRecord(tmpUserRecord);
      sessionContainer.setByPassPermission(true);
      sessionContainer.setUserIPAddress("127.0.0.1");
      
      // get the location information
      String locationStr = (String)this.getTarget();
      String[] locationArr = TextUtility.splitString(locationStr,RuleOperationConstant.SPLIT_STRING);      
      rootID = locationArr[0];
      parentID = locationArr[1];
      
      //get the message bean
      EmailMessageImpl emailMessage =  EmailMessageImpl.newInstance();
      emailMessage.setEmailMessageData((EmailMessageToRule)param[0]);
      
      DocumentEmailArchiveManager manager = new DocumentEmailArchiveManager(sessionContainer , dbConn,""); 
      /*rename subject Name if the email subject name dup*/
      emailMessage = manager.disposeSubject(sessionContainer,dbConn,emailMessage,rootID,parentID);
      //save email
//      if(!emailMessage.getOriContent().equals(emailMessage.getContent().toString())){
//        String blandStr = "";
//        emailMessage.setContent(blandStr);
//      }
      
      manager.saveWholeEmail(emailMessage,rootID,parentID);      
      
      // save email audit trail record
      try{
     	Date sentDate = emailMessage.getSendDate();
     	String sentDates = TextUtility.getDBDateTimeFormat().format(sentDate);
     	DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
        DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,dbConn);
        dmsEmailAuditTrail.setUserid(Utility.isEmpty(sessionContainer.getUserRecordID())?new Integer(0):sessionContainer.getUserRecordID());
        dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EMAIL_JOURNALING);
        dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_INBOUND);
        dmsEmailAuditTrail.setEmailFrom(Utility.isEmpty(emailMessage.getSender())?"":emailMessage.getSender());
        dmsEmailAuditTrail.setEmailTo(Utility.isEmpty(emailMessage.getTo())?"":emailMessage.getTo());
        dmsEmailAuditTrail.setEmailCc(Utility.isEmpty(emailMessage.getCc())?"":emailMessage.getCc());
        dmsEmailAuditTrail.setEmailBcc("");
        dmsEmailAuditTrail.setEmailSubject(Utility.isEmpty(emailMessage.getSubject())?"":emailMessage.getSubject());
        dmsEmailAuditTrail.setAttchSource("DMS");
        List attchList = new ArrayList();
        if(!Utility.isEmpty(emailMessage.getAttachments())){
          attchList = emailMessage.getAttachments();
        }
        Iterator iter = attchList.iterator();
        StringBuffer sb = new StringBuffer();
        while(iter.hasNext()){
       	EmailAttachmentImpl attch = (EmailAttachmentImpl)iter.next();
        	String attchName = attch.getAttachFileName();
        	sb.append(attchName+" ; ");
        }
        dmsEmailAuditTrail.setAttchName(sb.toString());
        dmsEmailAuditTrail.setSentDate(sentDates);
        dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
        dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
   	    dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
   	    dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
   	    dmsEmailAuditTrail.setUpdateCount(new Integer(0));
   	    dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
   	    dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
        dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
        log.debug("save email audit trail record.");
     }catch(Exception  e){
       log.error(e, e);
     }
      dbConn.commit();
    } catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx, appEx);
    } catch (Exception e) {
      log.debug(" Trigger a workflow occur Fatal Error.");
      log.error(e, e);     
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }
    log.debug("================= SaveEmailToDMSAction perform End ====================");
  }

}
